package com.atguigu.utils;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: JdbcUtil
 * Package: com.atguigu.utils
 * Description:
 *
 * @Author Lovxy
 * @Create 2023/5/15 14:17
 * @Version 1.0
 */
public class JdbcUtil {
    public static <T> List<T> queryList(Connection connection, String sql , Class<T> clz, boolean underScoreToCamel) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //创建集合用于存放结果
        ArrayList<T> list = new ArrayList<>();

        //编译SQL
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //执行查询操作
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        //遍历resultSet,将每行数据封装为T对象
        while (resultSet.next())
        {
            T t = clz.newInstance();
            //列遍历,将每个列设置进T对象
            for (int i = 1; i < columnCount + 1; i++) {
                String columnName = metaData.getColumnName(i);
                Object column = resultSet.getObject(columnName);

                if (underScoreToCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }
                //将列名与列值放入T对象
                BeanUtils.setProperty(t,columnName,column);

            }

            list.add(t);

        }

        //释放资源
        resultSet.close();
        preparedStatement.close();
        return list;
    }
}
